package com.guodi.map.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.tool.api.R;
import com.guodi.map.entity.MapDivision;
import com.guodi.map.entity.MapFunctionParam;
import com.guodi.map.entity.MapFunctionServer;
import com.guodi.map.service.IMapDivisionService;
import com.guodi.map.service.IMapFunctionParamService;
import com.guodi.map.service.IMapFunctionServerService;
import com.guodi.map.utils.VerificationUtil;
import com.guodi.system.feign.IDictClient;
import com.guodi.system.feign.ISysClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;


/**
 * @描述：功能服务表控制类
 * @作者: 代鹏刚
 * @日期: 2019-12-26
 */
@Validated
@RestController
@RequestMapping("/MapFunctionServer")
@Api(value = "API - MapFunctionServerController", tags = "功能服务表")
public class MapFunctionServerController extends BaseController {

    @Autowired
    private IMapFunctionServerService mapFunctionServerService;
    @Autowired
    private IMapFunctionParamService iMapFunctionParamService;
    @Resource
    private IDictClient iDictBizClient;
    @Resource
    private ISysClient iSysClient;

    @Resource
    private IMapDivisionService iMapDivisionService;

    /**
     * @描述: 根据实体属性分页查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-26
     **/
    @PostMapping("/listByEntity")
    @ApiOperation(value = " 根据实体属性分页查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "long", paramType = "query", example = "1"
    ), @ApiImplicitParam(name = "size", value = "每页显示数量", required = true, dataType = "long", paramType = "query", example = "10"
    ), @ApiImplicitParam(name = "keyWord", value = "关键字", required = false, dataType = "string", paramType = "query"
    ), @ApiImplicitParam(name = "dataSource", value = "数据来源", required = false, dataType = "string", paramType = "query"
    ), @ApiImplicitParam(name = "isShare", value = "共享状态", required = false, dataType = "Integer", paramType = "query"
    )})
    public R<Page<MapFunctionServer>> listByEntity(@ApiIgnore Page page, String keyWord, String dataSource, Integer isShare){
        List<String> orgIds = new ArrayList<>();
        if(StringUtils.isNotBlank(dataSource)) {
            orgIds.add(dataSource);
        }
        List<MapFunctionServer> mapFunctionServerList = mapFunctionServerService.listByEntity(page, keyWord, orgIds, isShare);
        //所有API参数
        List<MapFunctionParam> params = iMapFunctionParamService.list();
        for (MapFunctionServer mapFunctionServer: mapFunctionServerList) {
            //查询API参数
            List<MapFunctionParam> parameter = new ArrayList<>();
            if(params !=null &&!params.isEmpty()){
                for (MapFunctionParam param: params) {
                    if(mapFunctionServer.getId().equals(param.getFunServerId())){
                        parameter.add(param);
                    }
                }
            }
            mapFunctionServer.setParams(parameter);
            //字典信息--新基础运维
            if(null != mapFunctionServer.getBusiness()){
                String ywly = iDictBizClient.getValue("YWLY", mapFunctionServer.getBusiness()).getData();
                if(StringUtils.isNotBlank(ywly)){
                    mapFunctionServer.setBusinessName(ywly);
                }
            }
            if(StringUtils.isNotBlank(mapFunctionServer.getDataSource())){
                mapFunctionServer.setDataSourceName(iSysClient.getOrgName(Long.parseLong(mapFunctionServer.getDataSource())).getData());
            }
            //截取年份
            if(StringUtils.isNotBlank(mapFunctionServer.getEdition()) && mapFunctionServer.getEdition().length()>4){
                String edition = mapFunctionServer.getEdition();
                mapFunctionServer.setEdition(edition.substring(0,4));
            }
            //获取行政区划名
            if(StringUtils.isNotBlank(mapFunctionServer.getDivision())){
                MapDivision mapDivision = this.iMapDivisionService.mateByCode(mapFunctionServer.getDivision());
                mapFunctionServer.setDivisionName(mapDivision == null? null: mapDivision.getName());
            }
        }
        page.setRecords(mapFunctionServerList);
        return R.data(page);
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-26
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public R findById(String id) {
        if(StringUtils.isBlank(id)){
            return R.fail(StatusCode.ERROR_CODE_40005,"id不能为空");
        }
        MapFunctionServer mapFunctionServer = mapFunctionServerService.getById(id);
        LambdaQueryWrapper<MapFunctionParam> queryWrapper = (new QueryWrapper()).lambda();
        queryWrapper.eq(MapFunctionParam::getFunServerId,id);
        List<MapFunctionParam> list = iMapFunctionParamService.list(queryWrapper);
        List<MapFunctionParam> parameter = new ArrayList<>();
        for (MapFunctionParam param: list) {
            parameter.add(param);
        }
        mapFunctionServer.setParams(parameter);
        return R.data(mapFunctionServer);
    }

    /**
    * @描述:新增
    * @入参:
    * @出参:
    * @作者: 郑文彬
    * @日期: 2020/4/16 17:17
    **/
    @PostMapping(value = "/save", produces = "application/json;charset=UTF-8")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", value = "api参数 格式[{name:'',dataType:'',paramType:'',tags:'',required:''},...]", required = true,
                    dataType = "string", paramType = "query")
    })
    @ApiOperation(value = "新增")
    public R save(@Valid MapFunctionServer mapFunctionServer, String params ){
        if(!prepareData(mapFunctionServer, true)){
            return R.fail(StatusCode.ERROR_CODE_40005,"该服务名已经存在,请更换！");
        }
        //将json字符串转化成 List<MapFunctionParam>
        JSONArray jsonArr = JSONArray.fromObject(params);
        List<MapFunctionParam> paramList = new ArrayList<>();
        for (int i = 0; i <jsonArr.size() ; i++) {
            JSONObject obj = jsonArr.getJSONObject(i);
            MapFunctionParam mapFunctionParam=(MapFunctionParam)JSONObject.toBean(obj, MapFunctionParam.class);
            if(mapFunctionParam!=null){
                mapFunctionParam.setCreator(getUser().getUserId().toString());
                mapFunctionParam.setCreateTime(new Date());
                paramList.add(mapFunctionParam);
            }
        }
        String id = UuidUtil.get32UUID();
        mapFunctionServer.setId(id);
        if(StringUtils.isBlank(mapFunctionServer.getDataSource())){
            //获取当前用户ORGID,暂时默认用户不存在多个组织情况--新基础运维
            /*List<SysUser2org> sysUser2orgList = sysUser2orgService.listByUserId(this.getUser().getUserId().toString());
            if(!CollectionUtils.isEmpty(sysUser2orgList)){
                mapFunctionServer.setDataSource(sysUser2orgList.get(0).getOrgId());
            }else {
                //防止当前用户不属于任何一个组织，则设置默认值平台内置
                mapFunctionServer.setDataSource("1");
            }*/
        }
        //关联id
        for (MapFunctionParam param:paramList) {
            param.setId(UuidUtil.get32UUID());
            param.setFunServerId(id);
        }
        mapFunctionServerService.save(mapFunctionServer,paramList);
        return R.data(null);
    }

    /**
    * @描述: 修改
    * @入参:
    * @出参:
    * @作者: 郑文彬
    * @日期: 2020/4/21 14:23
    **/
    @PostMapping(value = "/update", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", value = "API参数 格式[{id,'',name:'',dataType:'',paramType:'',tags:'',required:''},...]", required = true,
                    dataType = "string", paramType = "query")
    })
    public R update(MapFunctionServer mapFunctionServer, String params ) {
        if(!prepareData(mapFunctionServer, false)){
            return R.fail(StatusCode.ERROR_CODE_40005,"该服务名已经存在,请更换！");
        }
        //将json字符串转化成 List<MapFunctionParam>
        JSONArray jsonArr = JSONArray.fromObject(params);
        List<MapFunctionParam> paramList = new ArrayList<>();
        for (int i = 0; i <jsonArr.size() ; i++) {
            JSONObject obj = jsonArr.getJSONObject(i);
            MapFunctionParam mapFunctionParam=(MapFunctionParam)JSONObject.toBean(obj, MapFunctionParam.class);
            if(mapFunctionParam!=null ){
                if(StringUtils.isBlank(mapFunctionParam.getId())){
                    mapFunctionParam.setId(UuidUtil.get32UUID());
                }
                mapFunctionParam.setCreator(getUser().getUserId().toString());
                mapFunctionParam.setCreateTime(new Date());
                mapFunctionParam.setModifier(getUser().getUserId().toString());
                mapFunctionParam.setModifyTime(new Date());
                mapFunctionParam.setFunServerId(mapFunctionServer.getId());
                paramList.add(mapFunctionParam);
            }
        }
        mapFunctionServerService.update(mapFunctionServer,paramList);
        return R.data(null);
    }

    /**
     * @描述: 根据主键删除
     * @入参: id
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-26
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "选中的数据ID", required = true, allowMultiple=true,dataType = "string", paramType = "query")
    })
    public R delete(String[] ids){
        if(ids.length > 0 && ids != null){
            List<String> idList = new ArrayList<>(ids.length);
            Collections.addAll(idList,ids);
            mapFunctionServerService.removeByIds(idList);
            LambdaQueryWrapper<MapFunctionParam> queryWrapper = (new QueryWrapper()).lambda();
            queryWrapper.in(MapFunctionParam::getFunServerId,idList);
            iMapFunctionParamService.remove(queryWrapper);
        }
        return R.data(null);
    }

    /**
     * @描述: 批量共享
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019/12/26 16:20
     **/
    @PostMapping("/updateIsShare")
    @ApiOperation(value = "批量共享")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "选中数据ID", required = true, allowMultiple=true,dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isShare", value = "是否共享(1:共享 2:不共享)", required = true, dataType = "string", paramType = "query")
    })
    public R updateIsShare(String[] ids, Integer isShare){
        if(ids != null && ids.length > 0){
            mapFunctionServerService.updateIsShare(ids,isShare);
            return R.data(null);
        }else {
            return R.fail(StatusCode.ERROR_CODE_40005,"id不能为空");
        }
    }

    private boolean prepareData(MapFunctionServer mapFunctionServer, boolean isSave) {
        //验证当前name是否已经存在
        List<MapFunctionServer> list = (List<MapFunctionServer>)mapFunctionServerService.listByMap(VerificationUtil.verifyMap(mapFunctionServer.getName(),null));
        if(isSave){
            if(list.size() > 0){
                return false;
            }
            mapFunctionServer.setCreator(getUser().getUserId().toString());
            mapFunctionServer.setCreateTime(new Date());
            //防止误修改
            mapFunctionServer.setModifier(getUser().getUserId().toString());
            mapFunctionServer.setModifyTime(new Date());
            return true;
        }else{
            if(list.size() > 0 && !list.get(0).getId().equals(mapFunctionServer.getId())){
                return false;
            }
            mapFunctionServer.setModifier(getUser().getUserId().toString());
            mapFunctionServer.setModifyTime(new Date());
            //防止误修改
            mapFunctionServer.setCreator(null);
            mapFunctionServer.setCreateTime(null);
            return true;
        }
    }
}
